package dave.hibernate.lab;

import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Transaction;

@WebServlet(description = "A hibernate serverlet", urlPatterns = { "/servlethib" })
public class HibernateServlet extends HttpServlet{
	 SessionFactory factory=null;
	 public void init(){
		 System.out.println("Inside init() method");
		 System.out.println ("Creating factory");
		 try
		 {
			 factory = new Configuration().configure().buildSessionFactory();
			 System.out.println("factory ready");
		 
		 }catch(Exception e1){ 
			 e1.printStackTrace();
			 System.out.println("" + e1);
		 }
	}
	 
	public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
	 System.out.println("Inside doPost() method");
	 res.setContentType("text/html");
	 PrintWriter out = res.getWriter();
	 String a = req.getParameter("name");
	 String b = req.getParameter("city");
	 String key = req.getParameter("key");
	 String s = req.getParameter("action");
	 PrintWriter pw = res.getWriter();
	 res.setContentType("text/html");
	 System.out.println("text1: " + a + " text2 : " + b + " text3 :" + key + " combo1 :" + s);
	 Transaction tx = null;
	 if(s.equals("add"))
	 {
	 try
	 {
	 Session session = factory.openSession();
	 tx = session.beginTransaction();
	 Employee employee1 = new Employee(a,b);
	 employee1.setName(a);
	 session.save(employee1);
	 tx.commit();
	 session.flush();
	 session.close();
	 pw.println("<h1> 1 Record added </h1>");
	 }
	 catch(Exception e1)
	 { e1.printStackTrace();
	 System.out.println("" + e1);
	 
	 pw.println("Exception Caught :" + e1);
	 
	 }
	 }
	 if(s.equals("remove"))
	 {
	 // CODE TO REMOVE A RECORD BASED ON EMP ID
	 }
	 if(s.equals("showall"))
	 {
	 // CODE TO LIST ALL EMPLOYEES
	 }
	 if(s.equals("find"))
		 {
		 // CODE TO FIND A RECORD BASED ON EMP ID
		 }
	 }//end if
}
